import React, { useEffect } from 'react';
import { useSnapshot } from 'valtio';
import { Drawer, Form } from 'szcd';
import { type ICommonPanelView } from '../../panels/base';
import styles from './index.module.less';
import { CloseOutlined } from '@ant-design/icons';
export interface IPanelView {
  isShow: boolean;
  current?: (ICommonPanelView & {
    component: React.FC<{ service: ICommonPanelView } & React.HTMLAttributes<HTMLDivElement>>;
  });
  mount: () => void;
  unmount: () => void;
}

const Panel: React.FC<{ service: IPanelView } & React.HTMLAttributes<HTMLDivElement>> = ({
  service,
  ...restProps
}) => {

  const snap = useSnapshot(service);

  // eslint-disable-next-line no-console
  console.count('panel render');

  useEffect(() => {
    service.mount();
    return () => {
      service.unmount();
    };
  }, [service]);

  // 手动触发render方案性能要差一点，通过useSnapshot的方式，可以合并多次rerender
  // const [_, refresh] = useState({});
  // useEffect(() => {
  //   const clear = subscribe(service, () => {
  //     refresh({});
  //   });
  //   return () => {
  //     clear();
  //   };
  // }, [service]);
  // console.count('render');

  return (
    <div {...restProps}>
      <div onClick={() => {
        service.isShow = false;
      }} className={
        styles.floatButton
        + ' ' +
        (snap.isShow ? styles.floatButtonActive : '')}
      >
        {/* ant-design 关闭按钮 */}
        <CloseOutlined />
      </div>
      <Drawer
        open={snap.isShow}
        width={510}
        closeIcon={false}
        title={snap.current?.title || ''}
        mask={false}
        getContainer={false}
      >
        {/* 我也不知道为什么snap.current 的变化 不会触发刷新 */}
        {/* 不能去掉，用来修复渲染失效问题 */}
        {/* <div style={{ display: 'none' }} data-id={snap.current?._refreshKey} /> */}
        {/* <pre>{JSON.stringify(snap.data, null, 2)}</pre>  */}
        <Form>
          {snap.current?._refreshKey && service.current && <service.current.component service={service.current} />}
        </Form>
      </Drawer>
    </div>
  );
};
export default Panel;
